﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using System.IO;

namespace System.Windows.Media.Media3D10
{
    /// <summary>
    /// Classe helper pour les textures DirectX10
    /// </summary>
    public static class Texture2DHelper
    {
        /// <summary>
        /// Converti un <see cref="System.Windows.Media.Brush"/> en <see cref="SlimDX.Direct3D10.Texture2D"/>
        /// </summary>
        /// <param name="brush"><see cref="System.Windows.Media.Brush"/> à convertir</param>
        /// <returns><see cref="SlimDX.Direct3D10.Texture2D"/> correpondant</returns>
        public static SlimDX.Direct3D10.Texture2D ToTexture2D(this Brush brush)
        {
            if (object.ReferenceEquals(brush, null))
                return null;
            ImageBrush imageBrush = brush as ImageBrush;
            if (imageBrush != null)
            {
                if (imageBrush.ImageSource is BitmapSource)
                    return ((BitmapSource)imageBrush.ImageSource).ToTexture2D();
            }
            throw new NotImplementedException();
        }

        /// <summary>
        /// Converti un <see cref="System.Windows.Media.Imaging.BitmapSource"/> en <see cref="SlimDX.Direct3D10.Texture2D"/>
        /// </summary>
        /// <param name="source"><see cref="System.Windows.Media.Imaging.BitmapSource"/> à convertir</param>
        /// <returns><see cref="SlimDX.Direct3D10.Texture2D"/> correpondant</returns>
        public static SlimDX.Direct3D10.Texture2D ToTexture2D(this BitmapSource source)
        {
            if (object.ReferenceEquals(source, null))
                return null;
            SlimDX.Direct3D10.Texture2D texture = null;
            using (MemoryStream stream = new MemoryStream())
            {
                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(source));
                encoder.Save(stream);
                stream.Position = 0;
                texture = SlimDX.Direct3D10.Texture2D.FromStream(Engine.Device10, stream, (int)stream.Length);
            }
            return texture;
        }
    }
}
